/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.openbookformat.tags;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author MUFEED
 */
public class HeadingTag  implements Tag{

    private int level;
    private boolean inTOC;
    private CompositeTag text;
    private CompositeTag toc_text;

    public HeadingTag(int level, boolean inTOC, CompositeTag text) {
        this(level, inTOC, text, null);
    }

    public HeadingTag(int level, boolean inTOC, CompositeTag text, CompositeTag toc_text) {
        this.level = level;
        this.inTOC = inTOC;
        this.text = text;
        this.toc_text = toc_text;
    }

    public boolean isInTOC() {
        return inTOC;
    }

    public void setInTOC(boolean inTOC) {
        this.inTOC = inTOC;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    public CompositeTag getText() {
        return text;
    }

    public void setText(CompositeTag text) {
        this.text = text;
    }

    public CompositeTag getToc_text() {
        return toc_text;
    }

    public void setToc_text(CompositeTag toc_text) {
        this.toc_text = toc_text;
    }
    
    public static final String TAG_PATTERN = 
            "\\s*<heading\\s+intoc='(\\d+)'\\s+level='(\\d+)'>\n" +
            "\\s*<text>(.*?)</text>\n" +
            "\\s*<toc_text\\s*/?>(.*?)(</toc_text>)?\n" +
            "\\s*</heading>";
    
    public static HeadingTag parse(String text) throws TagParsingException {
        if(!text.matches(TAG_PATTERN))
            throw new TagParsingException("Parsing error in FnTextTag:" + text);
        
        Pattern pattern = Pattern.compile(TAG_PATTERN);
        Matcher matcher = pattern.matcher(text);
       
        matcher.find();
        boolean inTOC = Integer.parseInt(matcher.replaceAll("$1")) == 1;
        int level = Integer.parseInt(matcher.replaceAll("$2"));
        CompositeTag ttext = TagUtil.textTagToCompositeTag(matcher.replaceAll("$3"));
        CompositeTag toc_text = matcher.replaceAll("$4").length() == 0? null:
                TagUtil.textTagToCompositeTag(matcher.replaceAll("$4"));
        
        return new HeadingTag(level, inTOC, ttext, toc_text);
    }

    @Override
    public String toString() {
        return "<heading level='"  + level + "' intoc='"
                +(inTOC?"1":"0") +"'>\n" +
                "\t<text>" + text + "</text>\n" +
                (toc_text == null? "\t<toc_text />":
                "\t<toc_text>" + toc_text + "</toc_text>") + "\n" +
                "</heading>\n";
    }


}
